import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:simple_tags/simple_tags.dart';

import '../../eventbus/EventBusUtil.dart';
import '../../eventbus/EventRefreshBase.dart';
import '../../eventbus/EventRefreshPart.dart';
import '../../util/BaseRequest.dart';
import '../../util/ColorUtil.dart';
import '../../util/ToastUtil.dart';
import '../../util/ViewUtil.dart';
import '../dto/PriceParm.dart';
import '../dto/PricePart.dart';


class SerialDataVC extends StatefulWidget {
  final VoidCallback callback;
  final PricePart pricePart;
  final PriceParm priceParm;
  const SerialDataVC({super.key, required this.callback, required this.pricePart, required this.priceParm});

  @override
  State<SerialDataVC> createState() => _SerialDataVCState();
}

class _SerialDataVCState extends State<SerialDataVC> {

  final formKey = GlobalKey<ShadFormState>();
  final dialogKey = GlobalKey<ShadFormState>();
  PriceParm? priceParm;

  final selectRequired = {
    '0': '非必填',
    '1': '必填',
  };
  final selectType= {
    '0': '输入',
    '1': '选择',
  };

  List<String> rules=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    priceParm=widget.priceParm;
    if(priceParm!.rule.isNotEmpty){
      List list=jsonDecode(priceParm!.rule);
      for (var item in list) {
        rules.add(item.toString());
      }
    }
    setState(() {

    });
  }

  @override
  Widget build(BuildContext context) {
    return

      ShadSheet(
        onClosing: (){
          debugPrint("关闭回调");
          widget.callback();
        },
        constraints: const BoxConstraints(minWidth: 800,maxWidth: 800),

        title: Row(
          children: [
            const Text('参数编辑'),
            const SizedBox(width: 50,),
            ViewUtil.doneIcon("保存", (){
              submit();
            })
          ],
        ),
        description: const Text(
            "编辑每一个参数的属性"),
        child:  ShadForm(
            key: formKey,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [

                Row(
                  children: [
                    Expanded(child: ShadInputFormField(
                      id: 'name',
                      initialValue: priceParm!.name,
                      label: const Text('参数名称'),
                      placeholder: const Text('请输入参数名称'),
                      validator: (v) {
                        if (v.isEmpty) {
                          return '请输入参数名称';
                        }
                        return null;
                      },
                    ),),
                    SizedBox(width: ViewUtil.screenWidth(10),),
                    Expanded(child: ShadInputFormField(
                      id: 'unit',
                      initialValue: priceParm!.unit,
                      label: const Text('单位'),
                      placeholder: const Text('请输入单位'),

                    ),),
                  ],
                ),


                const SizedBox(height: 10),

                Row(
                  children: [
                    Expanded(child:  ShadSelectFormField<String>(
                      id: 'required',

                      label: const Text('是否必填'),
                      minWidth: 350,
                      onChanged: handleChangeRequire,
                      initialValue: priceParm!.required.toString(),
                      options:[...selectRequired.entries
                          .map((e) => ShadOption(value: e.key, child: Text(e.value))),],
                      selectedOptionBuilder: (context, value) => value == 'none'
                          ? const Text('请选择是否必填')
                          : Text(selectRequired[value]!),
                      placeholder: const Text('是否必填'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择是否必填';
                        }
                        return null;
                      },
                    ),),
                    const SizedBox(width: 10,),
                    Expanded(child: ShadSelectFormField<String>(
                      id: 'type',
                      label: const Text('录入方式'),
                      minWidth: 350,
                      initialValue: priceParm!.type.toString(),
                      onChanged: handleChange,
                      options:[...selectType.entries
                          .map((e) => ShadOption(value: e.key, child: Text(e.value))),],
                      selectedOptionBuilder: (context, value) => value == 'none'
                          ? const Text('请选择录入方式')
                          : Text(selectType[value]!),
                      placeholder: const Text('录入方式'),
                      validator: (v) {
                        if (v == null) {
                          return '请选择录入方式';
                        }
                        return null;
                      },
                    ),)
                  ],
                ),
                const SizedBox(height: 10),

                Visibility(
                    maintainState: true,
                    visible:  priceParm!.type==0,
                    child: ShadInputFormField(
                      id: 'value',
                      initialValue: widget.priceParm.value,
                      label: const Text('录入数据'),
                      placeholder: const Text('请输入'),

                    )),

                Visibility(
                    visible:  priceParm!.type==1,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            const Text('选项'),
                            const SizedBox(width: 10,),
                            ViewUtil.addIcon('新增选项',(){
                              addTips();
                            }),
                          ],
                        ),

                        SimpleTags(
                          content: rules,
                          wrapSpacing: 4,
                          wrapRunSpacing: 4,
                          onTagPress: (tag) {
                            rules.remove(tag);
                            setState(() {

                            });},

                          tagContainerPadding: EdgeInsets.all(6),
                          tagTextStyle: TextStyle(color: ColorUtil.colorBlue),
                          tagIcon: const Icon(Icons.clear, size: 12),
                          tagContainerDecoration: BoxDecoration(
                            color: Colors.white,
                            border: Border.all(color: Colors.grey),
                            borderRadius: const BorderRadius.all(
                              Radius.circular(20),
                            ),
                          ),
                        ),

                      ],
                    )),

                const SizedBox(height: 16),


                // Row(
                //   mainAxisAlignment: MainAxisAlignment.center,
                //   children: [ViewUtil.textButton('保存', ViewUtil.screenWidth(400), ViewUtil.screenHeight(30), ViewUtil.radio(15),
                //       ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(25), (){
                //         submit();
                //       }),],
                // ),
              ],
            )),
      );
  }

  void addTips(){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              if (dialogKey.currentState!.saveAndValidate()) {
                var values= dialogKey.currentState!.value;
                var name=values["name"];
                rules.add(name);
                setState(() {

                });
                Navigator.pop(context);
              }
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('选项名称'),
                placeholder: const Text('请输入选项名称'),

                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入选项名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  void handleChange(var value){
    debugPrint(value);
    priceParm!.type=int.parse(value.toString());
    setState(() {

    });
  }

  void handleChangeRequire(var value){
    debugPrint(value);
    priceParm!.required=int.parse(value.toString());
    setState(() {

    });
  }


  void submit(){
    if (formKey.currentState!.saveAndValidate()) {


      var values= formKey.currentState!.value;
      var name=values["name"];
      var parentId=priceParm!.parentId;
      var value=values["value"];
      var unit=values["unit"];
      var required=values["required"];
      var type=values["type"];
      if(type=='1'&&rules.isEmpty){
        ToastUtil.showToast('请添加选项');
        return;
      }
      List ruleData=[];
      for(String item in rules){
        ruleData.add(item);
      }
      var id=widget.priceParm.id.isEmpty?null:widget.priceParm.id;
      var parm={
        "name":name,
        "parentId":parentId,
        "value":value,
        "unit":unit,
        "required":required,
        "type":type,
        "rule":ruleData,
        "id":id,
      };

      BaseRequest.postHttp("price/priceserialdataedit",parameters: parm, canTip: true, context: context, onSuccess: (data){

        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          eventBus.fire(EventRefreshPart());
        }
        Navigator.pop(context);
      }, onError: (error){

      });
    }

  }
}